import { Injectable } from '@nestjs/common';
import {
  CategoryListReqDto,
  CreateCategoryDto,
  UpdateCategoryDto,
} from './dto/category.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Like, Repository } from 'typeorm';
import { Category } from '../entities';

@Injectable()
export class CategoryService {
  constructor(
    @InjectRepository(Category)
    private readonly categoryRepository: Repository<Category>,
  ) {}
  save(data: CreateCategoryDto) {
    return this.categoryRepository.save(data);
  }

  findOne(params: Partial<Category>) {
    return this.categoryRepository.findOne({
      where: params,
    });
  }

  findOneByName(categoryName: string) {
    return this.categoryRepository.findOne({
      where: { categoryName },
    });
  }

  findAll(params: CategoryListReqDto) {
    return this.categoryRepository.find({
      where: {
        tag: Like(`%${params.tag || ''}%`),
      },
      order: { createdAt: 'DESC' },
    });
  }

  update(id: number, data: UpdateCategoryDto) {
    return this.categoryRepository.update(id, data);
  }

  remove(id: number) {
    return this.categoryRepository.delete(id);
  }
}
